var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//app与h5交互
function setupWebViewJavascriptBridge(callback) {
    try{
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }

        //和ios通信的方法
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'eastmoney://__bridge_loaded__'; // 自定义url
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() {
            document.documentElement.removeChild(WVJBIframe);
        }, 0);

        //和Android通信的方法
        if (window.WebViewJavascriptBridge) {
            callback(WebViewJavascriptBridge)
        } else {
            document.addEventListener( 'WebViewJavascriptBridgeReady' , function() {
                callback(WebViewJavascriptBridge) }, false );
        }
    }catch (e) {
        location.href = "#(ctx_path)/mobile/productList";
    }
}

/*setupWebViewJavascriptBridge(function(bridge) {
    //注册一个方法（方法名是“appCall”），客户端进行调用（方法名也是“appCall”），responseCallback是回调函数
    // app原生--> h5  ,alert(app原生)
    //open app need to CallBack "openApp" ,then send params:sessionId give h5
    bridge.registerHandler('openApp', function(params, responseCallback) {
        var sessionId = params.sessionId;
        var phone = params.phone;

        var result;//result 为0 session不存在，为1 session存在*!/
        responseCallback("123456");
        /!*if (sessionId == null || sessionId == 0){
            result = 0;
            responseCallback(result);
        }else{
            responseCallback(hasSession(phone,sessionId));
        }*!/
        //可以写自己想要的代码 。。。。。
    });

});*/

function hasSession(ctx ,func){
    //var customer = '#(session.customer ??)';
    alert("isAndroid："+isAndroid + "isIOS："+ isIOS);
    if(isAndroid || isIOS){
        setupWebViewJavascriptBridge(function(bridge) {
            bridge.callHandler(
                'openApp'
                , ''
                , function (responseData) {
                    console.log("JS received response:", responseData);
                    var data = eval('('+responseData+')');
                    var phone = data.phone;
                    var sessionId = data.sessionId;
                    if (createSession(ctx, phone, sessionId) == 1) {
                        if (func != null) {
                            func();
                        }
                    } else {
                        bridge.callHandler(
                            'toForward'
                            , '0'
                            , function (responseData) {
                                console.log("JS received response:", responseData);
                            }
                        );
                    }
                }
            );
        });
    }else{
        location.href = ctx +"/mobile/productList/showTelLogin"
    }
}


function createSession(ctx ,phone,sessionId){
    var result = 0;
    $.ajax({
        type: 'POST',
        url: ctx + '/mobile/productList/isExistSessionOfAPP.html',
        data:{"phone":phone,"sessionId":sessionId},
        cache:false,
        dataType: 'json',
        async:false,
        success: function(data){
            //if session存在 ，跳转到首页
            if (data.isSuccess == true) {
                result = 1;
            }else{
                //session 不存在，则还是当前登陆页面
                result = 0;
            }
        },
        error:function(data) {
            layer.msg('系统错误，请联系管理员！', {icon: 5,time:1500});
            console.log(data.msg);
        }
    });
    return result;
}